package com.structure.compositePattern.service.engine;

import com.structure.compositePattern.model.aggregates.TreeRich;
import com.structure.compositePattern.model.vo.EngineResult;
import com.structure.compositePattern.model.vo.TreeNode;
import com.structure.compositePattern.model.vo.TreeRoot;
import com.structure.compositePattern.service.logic.LogicFilter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 基础决策引擎功能
 * 主要提供决策树流程的处理过程，有点像通过链路的关系（性别、年龄）在二叉树中寻找果实节点的过程
 * 同时提供一个抽象方法，执行决策流程的方法供外部做具体的实现
 *
 * @author xiaobing
 * @version 1.0
 * @date 2021/9/8 8:10 下午
 */
@Slf4j
public abstract class EngineBase extends EngineConfig implements IEngine {

    @Override
    public abstract EngineResult process(Long treeId, String userId, TreeRich treeRich, Map<String, String> decisionMatter);

    protected TreeNode engineDecisionMaker(TreeRich treeRich, Long treeId, String userId, Map<String, String> decisionMatter) {
        TreeRoot treeRoot = treeRich.getTreeRoot();
        Map<Long, TreeNode> treeNodeMap = treeRich.getTreeNodeMap();
        // 规则树根ID
        Long rootNodeId = treeRoot.getTreeRootNodeId();
        TreeNode treeNodeInfo = treeNodeMap.get(rootNodeId);
        //节点类型[NodeType]；1子叶、2果实
        while (treeNodeInfo.getNodeType().equals(1)) {
            String ruleKey = treeNodeInfo.getRuleKey();
            LogicFilter logicFilter = logicFilterMap.get(ruleKey);
            String matterValue = logicFilter.matterValue(treeId, userId, decisionMatter);
            //第一次是man，第二次是29
            Long nextNode = logicFilter.filter(matterValue, treeNodeInfo.getTreeNodeLinkList());
            //第一次nextNode是11，第二次是111（是果实了）
            treeNodeInfo = treeNodeMap.get(nextNode);
            log.info("决策树引擎=>{} userId：{} treeId：{} treeNode：{} ruleKey：{} matterValue：{}", treeRoot.getTreeName(), userId, treeId, treeNodeInfo.getTreeNodeId(), ruleKey, matterValue);
        }
        return treeNodeInfo;
    }
}
